const {
  resolve
} = require('core-js/fn/promise');
const mysql = require('mysql');
module.exports = class Model {
  //数据查询的基类,封装了数据库的常见操作
  // 创建连接对象
  static conn = null;
  //创建连接方法
  static connection() {
    Model.conn = mysql.createConnection({
      host: 'localhost',
      user: 'root',
      password: 'admin',
      database: 'vue-store'
    });
    Model.conn.connect(err => {
      if (err) {
        console.log('数据库连接失败，原因是:' + err.message);
      }
    })
  }
  //关闭连接方法
  static end() {
    if (Model.conn !== null) {
      Model.conn.end();
    }
  }
  //通用查询方法
  static query(sql, params = []) {
    return new Promise((resolve, reject) => {
      this.connection();
      Model.conn.query(sql, params, (err, results) => {
        if (err) {
          reject(err);
        } else {
          resolve(results);
        }
      });
      this.end();
    });
  }
}